#include <iostream>
#include <mysql/mysql.h>
#include <string>

using namespace std;

const char* host = "localhost";
const char* user = "silence";
const char* passward = "komalijiang";
const char* db = "connect";
const unsigned int port = 3077;

int main()
{
    // 创建MySQL句柄
    MYSQL* my = mysql_init(nullptr);
    if(my == nullptr)
    {
        cerr << "mysql_init error " << endl;
        return 1;
    }

    // 进行连接数据库
    if(!mysql_real_connect(my,host,user,passward,db,port,nullptr,0))
    {
        cerr << "mysql_real_connect error" << endl;
        return 2;
    }
    cout << "mysql_init success " << endl;
    // int op = mysql_set_character_set(my,"latin1");
    // 进行MySQL操作
    // 进行select查询
    string sql = "select * from stu";
    int n = mysql_query(my,sql.c_str());
    if(n == 0) cout << "当前SQL执行成功" <<endl;
    else 
    {
        cout << "当前SQL执行失败" <<endl;
        return 3;
    }
    // 拿到查询后的结果
    MYSQL_RES* res = mysql_store_result(my); 
    if(res == nullptr)
    {
        cerr << "mysql_store_result err" << endl;
        return 4;
    }
    // 对查询后的结果进行解析
    // uint64_t rows = mysql_num_rows(res);
    // unsigned int fields = mysql_num_fields(res);
    // MYSQL_ROW mysql_fetch_row(MYSQL_RES *result);
    // MYSQL_FIELD * mysql_fetch_field(MYSQL_RES *result);
    
    // 获取行，列
    int row = mysql_num_rows(res);
    int cols = mysql_num_fields(res);

    // 打印列属性名称
    MYSQL_FIELD * fields = mysql_fetch_field(res);
    for(int i = 0;i<cols;i++)
    {
        cout << fields[i].name << '\t';
    }
    cout << endl;

    // 打印数据
    for(int i = 0;i<row;i++)
    {
        MYSQL_ROW rows = mysql_fetch_row(res);
        for(int j = 0;j<cols;j++)
        {
            cout << rows[j] << '\t';
        }
        cout << endl;
    }

    // string sql;
    // while(true)
    // {
    //     cout<<"请输入你需要操作的SQL语句: "<<endl;
    //     if(!getline(cin,sql) || sql == "quit") break;
    //     int n = mysql_query(my,sql.c_str());
    //     if(n == 0) cout << "当前SQL执行成功" <<endl;
    //     else cout << "当前SQL执行失败" <<endl;
    // }
    // 关闭MySQL句柄
    mysql_close(my);
    return 0;
}

// int main()
// {
//     std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;
//     return 0;
// }